const computedBehavior = require("miniprogram-computed").behavior;
const recordsStore = require('../../../stores/records');
const STORAGE_KEYS = require("../../../configs/STORAGE_KEYS");
const { getFinalScores } = require('../../../business/score')

Component({
  behaviors: [computedBehavior],
  /**
   * 组件的属性列表
   */
  properties: {
    currentPlayers: {
      type: Array,
      default: [],
    },
    leftStickNum: {
      type: Number,
      default: 0,
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    orderScores: [50, 10, -10, -30],
    finals: [],
    // 备注
    remark: '',
  },

  lifetimes: {
    attached() {
      this.setFinals()
      this.setRemark()
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    backToHome() {
      recordsStore.storeCurrentToHistory(this.data.remark)
      recordsStore.clearCurrent()
      wx.reLaunch({
        url: '/pages/index/index',
      });
    },
    handleAgain() {
      recordsStore.storeCurrentToHistory(this.data.remark)
      recordsStore.clearCurrent(true)
      wx.reLaunch({ url: '/pages/start/start' })
    },
    setFinals() {
      const { currentPlayers, leftStickNum } = this.data;
      const finals = [...currentPlayers].sort((a, b) => b.point - a.point)
      const icons = ['first', 'second', 'third', 'pig']
      // 最终得点数据
      const finalPoints = finals.map(final => final.point);
      const finalScores = getFinalScores(finalPoints, leftStickNum, this.data.orderScores);
      finals.forEach((final, index) => {
        final.score = finalScores[index];
        final.icon = icons[index]
        final.score = Math.round(final.score * 100) / 100;
      })
      this.setData({ finals })
    },
    setRemark() {
      const gameNum = wx.getStorageSync(STORAGE_KEYS.CURRENT_GAME_NUM);
      if (gameNum) {
        const gameRemarks = wx.getStorageSync(STORAGE_KEYS.GAME_REMARKS) || {};
        const remark = gameRemarks[gameNum];
        this.setData({ remark })
      }
    }
  },
})